﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using DAL.Models;
using DAL.BAL;
using DevExpress.Xpf.Grid;

namespace WpfClient.Windows
{
    /// <summary>
    /// Interaction logic for Calendar.xaml
    /// </summary>
    public partial class Calendar : Window
    {
        private DateTime CalendarDate = DateTime.Today;

        public Calendar()
        {
            InitializeComponent();

            gridControl1.View.AllowEditing = false;

            SetDateToControl(CalendarDate);

            CreateContextMenu();

            bRemoveToCurrent.IsVisible = false;
            
            var OpenedOldEvents = Business.GetOpenCalendarEventsFromPrevDays(CalendarDate);

            if (OpenedOldEvents.Count() != 0)
                if (MessageBox.Show("Есть некоторые события из предыдущих дней, которое не сделаны. Вы хотите перемистить их в текущий день?", WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
                {
                    RemoveToCurrentDay(OpenedOldEvents.ToList());

                    Business.Save();
                }

            Refresh();
        }

        private void Refresh()
        {
            gridControl1.ItemsSource = Business.GetCalendarEvents(CalendarDate).ToList() ;

            gridControl1.ExpandAllGroups();
        }

        private void SetDateToControl(DateTime date)
        {
            string text = string.Format("{0}.{1}.{2}", CalendarDate.Day.ToString(), CalendarDate.Month.ToString(), CalendarDate.Year.ToString());

            bDate.Content = text;
        }

        private void bPrev_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            if (sender == bPrev)
                CalendarDate = CalendarDate.AddDays(-1);
            else
                CalendarDate = CalendarDate.AddDays(1);

            if (CalendarDate != DateTime.Today)
                bRemoveToCurrent.IsVisible = true;
            else
                bRemoveToCurrent.IsVisible = false;

            SetDateToControl(CalendarDate);

            Refresh();
        }

        private void bRefresh_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            Refresh();
        }

        private void CreateContextMenu()
        {
            var statuses = Business.GetCalendarEventStatuses();

            foreach (CalendarEventStatus ces in statuses)
            {
                DevExpress.Xpf.Bars.BarButtonItem button = new DevExpress.Xpf.Bars.BarButtonItem();

                button.Content = ces.StatusName;

                button.Tag = ces;

                button.ItemClick += buttonStatus_ItemClick;

                bStatus.ItemLinks.Add(button);
            }

            var users = from n in Business.GetUsers()
                        where (n.Active == true && n.Id != Business.currentUser.Id)
                        select n;

            foreach (User user in users)
            {
                DevExpress.Xpf.Bars.BarButtonItem button = new DevExpress.Xpf.Bars.BarButtonItem();

                button.Content = user.UserName;

                button.Tag = user;

                button.ItemClick += buttonAssign_ItemClick;

                bAssignTo.ItemLinks.Add(button);
            }

        }

        private void buttonStatus_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            foreach (int handle in (gridControl1.View as TableView).GetSelectedRowHandles())
            {
                CalendarEvent calendarEvent = (CalendarEvent)gridControl1.GetRow(handle);

                if (calendarEvent != null)
                {
                    calendarEvent.CalendarEventStatus = (CalendarEventStatus)(sender as DevExpress.Xpf.Bars.BarButtonItem).Tag;
                }
            }

            Business.Save();
        }

        private void buttonAssign_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            foreach (int handle in (gridControl1.View as TableView).GetSelectedRowHandles())
            {
                CalendarEvent calendarEvent = (CalendarEvent)gridControl1.GetRow(handle);

                if (calendarEvent != null)
                {
                    List<CalendarEvent> list = new List<CalendarEvent>();

                    list.Add(calendarEvent);

                    Business.ChangeEventTime((User)(sender as DevExpress.Xpf.Bars.BarButtonItem).Tag, DateTime.Today, list);

                    calendarEvent.User = (User)(sender as DevExpress.Xpf.Bars.BarButtonItem).Tag;

                    calendarEvent.CalendarEventStatus = (from n in Business.GetCalendarEventStatuses()
                                                         where n.Id == 1
                                                         select n).FirstOrDefault();
                }
            }

            Business.Save();

            Refresh();
        }

        private void bRemoveToCurrent_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            foreach (int handle in (gridControl1.View as TableView).GetSelectedRowHandles())
            {
                CalendarEvent calendarEvent = (CalendarEvent)gridControl1.GetRow(handle);

                if (calendarEvent != null)
                {
                    List<CalendarEvent> list = new List<CalendarEvent>();

                    list.Add(calendarEvent);

                    RemoveToCurrentDay(list);
                }
            }

            Business.Save();

            Refresh();
        }

        private void RemoveToCurrentDay(List<CalendarEvent> list)
        {            
            Business.ChangeEventTime(Business.currentUser, DateTime.Today, list);

            foreach (CalendarEvent ce in list)
            {
                ce.EventDate = DateTime.Today;
            }
        }

        private void bDelete_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            if (MessageBox.Show(WpfClient.Properties.Resources.AreYouSureYouWantDelete,
              WpfClient.Properties.Resources.Warning, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
            {
                try
                {
                    int[] handles = (gridControl1.View as TableView).GetSelectedRowHandles();

                    for(int i = handles.Count() - 1; i >= 0; i--)
                    {
                        DAL.Models.CalendarEvent ec = (DAL.Models.CalendarEvent)gridControl1.GetRow(handles[i]);

                        Business.DeleteObject(ec);

                        //(gridControl1.View as GridViewBase).DeleteRow(handles[i]);
                    }

                    Business.Save();

                    Refresh();
                }
                catch (Exception e1)
                {                  
                    MessageBox.Show(e1.Message, WpfClient.Properties.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);

                    Business.Cancel();

                    Refresh();
                }
            }
        }

        private void tableView_ShowGridMenu(object sender, GridMenuEventArgs e)
        {
            if (e.MenuType == GridMenuType.RowCell)
            {
                GridCellMenuInfo menuInfo = (GridCellMenuInfo)e.MenuInfo;

                int handle = menuInfo.Row.RowHandle.Value;

                DAL.Models.CalendarEvent ec = (DAL.Models.CalendarEvent)gridControl1.GetRow(handle);

                if (ec != null)
                {
                    if (ec.Vacancy == null)
                        bShowVacancy.IsEnabled = false;
                    else
                        bShowVacancy.IsEnabled = true;
                }
            }
        }

        private void bShowVacancy_ItemClick(object sender, DevExpress.Xpf.Bars.ItemClickEventArgs e)
        {
            CalendarEvent ce = (CalendarEvent)gridControl1.GetFocusedRow();

            if (ce != null)
            {
                if (ce.Vacancy != null)
                {
                    VacancyEdit vacancyEdit = new VacancyEdit(ce.Vacancy, false, Business.CanEditVacancies());

                    if (vacancyEdit.ShowDialog() == false)
                    {
                        Business.Cancel();

                        Business.Refresh(System.Data.Objects.RefreshMode.StoreWins, ce.Vacancy);
                    }
                    else
                    {
                        Business.Save();
                    }
                }
            }
        }
    }
}
